package com.xsherl.leetcode.solution;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import com.xsherl.leetcode.utils.ArrayUtils;
import com.xsherl.leetcode.utils.PrintUtils;

public class RotateImage {

    /**
     * 将图像顺时针旋转 90 度，
     * 1. 行号递增顺序由上至下修改为由右至左
     * 2. 列号递增顺序由左到右修改为由上到下
     *  因此 matrix[i][j] = matrix[j][n - i - 1]
     *  比如3x3的矩阵：(1, 0) => (0, 1)
     *               (0, 1) => (1, 2)
     *               (2, 1) => (1, 0)
     * 所以我们每次旋转4个点，只需要旋转中心点上面部分的点就行了。
     * 而由于旋转过的点不需要旋转，所以每次旋转后需要更新旋转的边界
     *
     * @param matrix matrix.length == n
     *               matrix[i].length == n
     *               1 <= n <= 20
     *               -1000 <= matrix[i][j] <= 1000
     */
    public void rotate(int[][] matrix) {
        int len = matrix.length - 1, innerLen = len;
        for (int i = 0; i < len; i++){
            for (int j = i; j < innerLen; ++j){
                rotate(matrix, i, j);
            }
            innerLen--;
        }
    }

    private void rotate(int[][] matrix, int i, int j){
        int len = matrix.length;
        int x = i, y = j;
        int t = matrix[i][j];
        for (int k = 0; k < 3; ++k){
            int pre = matrix[j][len - i - 1];
            matrix[j][len - i - 1] = t;
            t = pre;
            int m = j;
            j = len - i - 1;
            i = m;
        }
        matrix[x][y] = t;
    }

    public static void main(String[] args) {
        int[][] matrix = ArrayUtils.parseArray("" +
                "[[1,2,3],[4,5,6],[7,8,9]]" +
                "", int[].class);
        PrintUtils.println(matrix);
        new RotateImage().rotate(matrix);
        PrintUtils.println(matrix);
        int[][] output = ArrayUtils.parseArray("" +
                "[[7,4,1],[8,5,2],[9,6,3]]" +
                "", int[].class);
        Assert.isTrue(ArrayUtil.equals(matrix, output));
    }
}
